package com.project.shiro;

import com.project.bean.UserBean;
import com.project.result.GlobalHandleException;
import com.project.service.IUserService;
import com.project.util.WebUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class JWTRealm extends AuthorizingRealm {
    @Resource
    private IUserService userInfoService;


//    @Resource
//    private IGradeService functionInfoService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户对象
        UserBean userBean = (UserBean) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        List<RoleBean> roleInfoBeans = userBean.getRoleBeanList();
//        List<GradeBean> functionInfoBeans = functionInfoService.findByRoleList(roleInfoBeans);
//        for (RoleBean role : roleInfoBeans) {
//            //添加角色
//            simpleAuthorizationInfo.addRole(role.getName());
//        }
//        for (GradeBean function : functionInfoBeans) {
//            //添加权限
//            simpleAuthorizationInfo.addStringPermission(function.getName());
//        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取用户token
        String token = (String)authenticationToken.getPrincipal();
        if(token == null){
            return new SimpleAuthenticationInfo(null,"",getName());
        }
        UserBean userBean = null;
        try {
            userBean = WebUtil.verifyToken(token,userInfoService);
        } catch (GlobalHandleException e) {
            e.printStackTrace();
        }
        if(userBean == null){
            return new SimpleAuthenticationInfo(null,"",getName());
        }

        return new SimpleAuthenticationInfo(userBean,token,getName());
    }
}
